const co = require('co');
const moment = require('moment');
const models = require('../models');
const logger = require('../utils/logger');
const config = require('../config/config.json');
var Sequelize = require('sequelize');
const mail = require('./mail');
const Op = Sequelize.Op


let saveCollectionData = co.wrap(function* (data) {
    let result = {
        error: '',
        modelData: null
    }
    try {
        let appDataCollection = null;
        if (data.dataType == 'subscribe') {
            if (!data.email || data.email.length == 0) {  // subscribe need an user email addr
                result.error = 'no email';
                return result;
            }
            appDataCollection = yield models.AppDataCollection.findOrCreate({
                where: { dataType: 'subscribe', email: data.email },
                defaults: { status: '0', accountName: data.accountName, appVersion: data.appVersion }
            },

            );
        } else if (data.dataType == 'feedback') {   // feedback need the user email addr and the feedback content.
            if (!data.email || data.email.length == 0) {
                result.error = 'no email';
                return result;
            }
            if (!data.content || data.content.length == 0) {
                result.error = 'no content';
                return result;
            }

            let count = yield models.AppDataCollection.count({
                where:
                {
                    dataType: { [Op.eq]: 'feedback' },
                    email: { [Op.eq]: data.email },
                    accountName: { [Op.eq]: data.accountName },
                    content: { [Op.eq]: data.content },
                    createdAt: { [Op.gte]: moment().subtract(1, 'hours') }
                }
            });
            if (count > 0) {
                logger.info('feedback data duplicated, ignore it!');
                result.error = 'duplicated';
                return result;
            }

            appDataCollection = yield models.AppDataCollection.create(
                {
                    dataType: data.dataType,
                    accountName: data.accountName,
                    email: data.email,
                    content: data.content,
                    appVersion: data.appVersion,
                    remark: data.remark,
                    status: '0',
                }
            );
        }
        // DONE 
        result.modelData = appDataCollection;
        return result;

    } catch (error) {
        logger.error(error);
        result.error = 'internal error';
        return result;
    }
});

let handleCollectionData = co.wrap(function* (data) {
    try {
        const result = yield saveCollectionData(data);
        const appDataCollection = result.modelData;
        if (appDataCollection == null) {
            return result.error;
        }
        if (appDataCollection.dataType === 'feedback') {
            const feedbackInfo = {
                fromMail: appDataCollection.email,
                fromEosAccount: appDataCollection.accountName,
                feedbackTime: moment(appDataCollection.createdAt).format('YYYY-MM-DD HH:mm:ss'),
                content: appDataCollection.content
            };
            mail.forwardFeedbackContent(feedbackInfo, function () {
                appDataCollection.status = '1';
                appDataCollection.save();
            });
        }
    } catch (error) {
        logger.error(error);
        return 'internal error';
    }
    return 'success';
});

let findSubscribeList = co.wrap(function* (params) {
    let datalist = [];
    try {
        datalist = yield models.AppDataCollection.findAll(
            {
                limit: params.count || 100,
                where: {
                    dataType: {
                        [Op.eq]: 'subscribe'
                    }
                },
                order: [["createdAt", "desc"]]
            }
        );
    } catch (error) {
        logger.error(error);
    }
    return datalist;
});

module.exports = {
    handleCollectionData,
    findSubscribeList
};

